﻿using System;
using System.Configuration;
using System.Reflection;

namespace BlobNet.Base.DataProviders
{
    internal static class DataProviderFactory
    {
        private static readonly object ReadLock = new object();
        private static volatile IDataProvider _provider;

        public static IDataProvider Provider
        {
            get
            {
                if (_provider == null)
                    lock (ReadLock)
                        if (_provider == null)
                        {
                            string appSetting = ConfigurationManager.AppSettings["DataProviderClass"]; //TODO: SETTINGS USING DI
                            if (appSetting != null)
                            {
                                GetInstance(appSetting);
                            }
                        }

                return _provider;
            }
            //TODO: GET RID of this by dependency injection, this is just to be able to mock for unit tests
            internal set { _provider = value; }
        }

        private static void GetInstance(string appSetting)
        {
            string[] strings = appSetting.Split(';');
            string assemblyName = string.Empty, typeName = string.Empty;
            foreach (string s in strings)
            {
                string[] source = s.Split(new[] {"="}, 2, StringSplitOptions.None);
                if (source[0].ToLower() == "assembly")
                    assemblyName = source[1];
                else
                    typeName = source[1];
            }

            Assembly assembly = Assembly.Load(assemblyName);
            Type type = assembly.GetType(typeName);
            _provider = (IDataProvider) Activator.CreateInstance(type, null);
        }
    }
}